<?php

use Doraemon\tools\Log;
use Doraemon\tools\IdParse;
use Doraemon\model\CommentMasterStat as DbCommentMasterStat;
use Doraemon\cache\CommentsCounter as cComment;
use Doraemon\model\Comment as DbComment;

class SyncCommentsAction extends ActionPlugin
{
    const _DATABASE_ = 'hhzhome_content';

    const _LIKETABLE = 'hhz_comments_like_';

	public function main()
	{
		// 调试日志
		Log::info('评论统计接收到的订阅信息', $this->messageBody);
        if ($this->messageBody['database'] != self::_DATABASE_) throw new \Exception('数据库错误');

        if (empty($this->messageBody['data'])) throw new \Exception('数据错误');

        $table = $this->messageBody['table'] ?? '';
        if (mb_strpos($table, self::_LIKETABLE) !== false) {
            $this->handleCommentLike();
            $this->setSuccess();
        } else {
            $this->handleComment();
            $this->setSuccess();
        }


	}

	public function handleComment()
    {
        switch ($this->messageBody['type']) {
            case "insert" :
                $res = $this->syncCommentInsert($this->messageBody['data']);
                Log::info('新增评论信息统计结束', ['res' => $res, 'data' => $this->messageBody['data']]);
                break;
            case "update" :
                $res = $this->syncCommentUpdate($this->messageBody['data']);
                Log::info('删除评论信息统计结束', ['res' => $res, 'data' => $this->messageBody['data']]);
                break;
        }
        return true;
    }

    public function handleCommentLike()
    {
        switch ($this->messageBody['type']) {
            case "insert" : //第一次点赞
                $res = $this->syncLikeInsert($this->messageBody['data']);
                Log::info('评论点赞新增信息统计结束', ['res' => $res, 'data' => $this->messageBody['data']]);
                break;
            case "update" : //再次点赞、取消赞
                $res = $this->syncLikeUpdate($this->messageBody['data']);
                Log::info('删除评论点赞信息统计结束', ['res' => $res, 'data' => $this->messageBody['data']]);
                break;
        }
        return true;
    }

	public function syncCommentInsert($data)
    {
        if ($data['type'] == 1) { //主评论
            $master = DbCommentMasterStat::get('id', ['obj_id' => $data['obj_id'], 'obj_type'=>$data['obj_type'], 'origin_id' => $data['id']]);
            if (!empty($master) ) {
                Log::info('SyncComments#syncCommentInsert#data exists', ['master' => $master]);
                return false;
            }
            $insert['obj_id'] = $data['obj_id'];
            $insert['obj_type'] = $data['obj_type'];
            $insert['origin_id'] = $data['id'];
            $insert['uid'] = $data['uid'];
            $isEmoji = \Doraemon\tools\Filter::filterEmoji($data['content']); //过滤emoji
            if (!empty($isEmoji)) {
                $isEmoji = \Doraemon\tools\Emoticon::filterEmoticon($data['content']); //过滤好好住表情
            }
            $insert['is_only_emoji'] = empty($isEmoji) ? 1 : 0;
            $insert['is_owner'] = $data['is_owner'];
            $insert['add_time'] = $data['addtime'];
            $insert['status'] = $data['status'];
            $insert['top_level'] = $data['top_level'] ?? 30;
            return DbCommentMasterStat::addData($insert);

        } else { // 子评论
            $master = DbCommentMasterStat::get('*', ['obj_id' => $data['obj_id'], 'obj_type'=>$data['obj_type'], 'origin_id' => $data['root_id']]);
            if (empty($master)) {
                Log::info('SyncComments#syncCommentInsert#master is not exists', []);
                return false;
            }

            //兼容乐高未审核评论
            if ($data['status'] != DbCommentMasterStat::STATUS_NORMAL) {
                Log::info('SyncComments#syncCommentInsert#sub is not status', []);
                return true;
            }

            while(!cComment::getLock($data['obj_id'], $data['root_id'], $data['obj_type'])) { //拿不到锁阻塞等待，锁自动过期时间2s
                sleep(0.2);
            }

            $update['reply_num'] = $master['reply_num']+1;
            $update['reply_like_count'] = $master['reply_num']+1+$master['like_num'];
            if ($data['is_owner'] && !$master['is_owner']) { //作者回复标注
                $update['is_owner'] = 1;
            }
            $res = DbCommentMasterStat::update($update, ['id' => $master['id']]);
            cComment::delLock($data['obj_id'], $data['root_id'], $data['obj_type']);
            return $res;
        }
    }

    public function syncCommentUpdate($data){
        if ($data['type'] == 1) { //主评论
            $master = DbCommentMasterStat::get('*', ['obj_id' => $data['obj_id'], 'obj_type'=>$data['obj_type'], 'origin_id' => $data['id']]);
            if (empty($master) ) {
                Log::info('SyncComments#syncCommentUpdate#data not exists', []);
                return false;
            }

            $update['status'] = $data['status'];
            return DbCommentMasterStat::update($update, ['id' => $master['id']]);

        } else { // 子评论
            $master = DbCommentMasterStat::get('*', ['obj_id' => $data['obj_id'], 'obj_type'=>$data['obj_type'], 'origin_id' => $data['root_id']]);
            if (empty($master)) {
                Log::info('SyncComments#syncCommentUpdate#master is not exists', []);
                return false;
            }

            while(!cComment::getLock($data['obj_id'], $data['root_id'], $data['obj_type'])) { //拿不到锁阻塞等待，锁自动过期时间2s
                sleep(0.2);
            }

            if ($data['status'] == DbCommentMasterStat::STATUS_NORMAL) {
                $update['reply_num'] = $master['reply_num']+1;
                $update['reply_like_count'] = $master['reply_num']+1+$master['like_num'];
            } else {
                $replyNum = $master['reply_num'] - 1 < 0 ? 0 : $master['reply_num']-1;
                $update['reply_num'] = $replyNum;
                $update['reply_like_count'] = $replyNum+$master['like_num'];
            }

            if ($data['is_owner']) { //如果被删除的回复是作者回复，验证评论是否为作者评论，评论下的回复还有没有作者回复，改变状态
               $isOwner = DbComment::getChildOwnerCount($data['obj_id'], $data['root_id']) > 0 || $master['uid'] == IdParse::getUid($master['obj_id']) ? 1 : 0;
               if ($isOwner != $master['is_owner']) {
                   $update['is_owner'] = $isOwner;
               }
            }

            $res = DbCommentMasterStat::update($update, ['id' => $master['id']]);
            cComment::delLock($data['obj_id'], $data['root_id'], $data['obj_type']);
            return $res;

        }
    }

    public function syncLikeInsert($data)
    {
        //临时修改
        if ($data['obj_type'] == 101) {
            $objType = $data['obj_type'];
        } else {
            $objType = IdParse::getType($data['obj_id']);
        }
        $master = DbCommentMasterStat::get('*', ['obj_id' => $data['obj_id'], 'obj_type'=> $objType, 'origin_id' => $data['comments_id']]);
        if (empty($master)) {
            Log::info('SyncComments#syncLikeInsert#master is not exists', []);
            return false;
        }
        while(!cComment::getLock($data['obj_id'], $data['comments_id'], $objType)) { //拿不到锁阻塞等待，锁自动过期时间2s
            sleep(0.2);
        }
        $update['like_num'] = $master['like_num']+1;
        $update['reply_like_count'] = $master['like_num']+1+$master['reply_num'];
        $res = DbCommentMasterStat::update($update, ['id' => $master['id']]);
        cComment::delLock($data['obj_id'], $data['comments_id'], $objType);
        return $res;
    }

    public function syncLikeUpdate($data)
    {
        //临时修改
        if ($data['obj_type'] == 101) {
            $objType = $data['obj_type'];
        } else {
            $objType = IdParse::getType($data['obj_id']);
        }
        $master = DbCommentMasterStat::get('*', ['obj_id' => $data['obj_id'], 'obj_type'=> $objType, 'origin_id' => $data['comments_id']]);
        if (empty($master)) {
            Log::info('SyncComments#syncLikeUpdate#master is not exists', []);
            return false;
        }
        while(!cComment::getLock($data['obj_id'], $data['comments_id'], $objType)) { //拿不到锁阻塞等待，锁自动过期时间2s
            sleep(0.2);
        }
        if ($data['status'] == \Doraemon\model\CommentLike::STATUS_DELETE) {
            $likeNum = $master['like_num']-1 < 0 ? 0 : $master['like_num']-1;
            $update['like_num'] = $likeNum;
            $update['reply_like_count'] = $likeNum+$master['reply_num'];
        } else {
            $update['like_num'] = $master['like_num']+1;
            $update['reply_like_count'] = $master['like_num']+1+$master['reply_num'];
        }
        $res = DbCommentMasterStat::update($update, ['id' => $master['id']]);
        cComment::delLock($data['obj_id'], $data['comments_id'], $objType);
        return $res;
    }

}
